package com.erp.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.order.domain.bo.ErpSellerOrderLogBo;
import com.erp.order.domain.bo.ErpSendOutGoodsBo;
import com.erp.order.domain.vo.ErpSendOutGoodsVo;
import com.erp.order.mapper.*;
import com.erp.order.service.IErpSellerOrderLogService;
import com.erp.order.service.IErpSendOutGoodsService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.OrderLogType;
import com.ruoyi.common.core.enums.OrderProcessFlag;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.order.api.domain.*;
import com.ruoyi.statistics.api.domain.ErpChildOrderStatistics;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 订单发货Service业务层处理
 *
 * @author erp
 * @date 2023-03-31
 */
@RequiredArgsConstructor
@Service
public class ErpSendOutGoodsServiceImpl implements IErpSendOutGoodsService {

    private final ErpSendOutGoodsMapper baseMapper;
    private final ErpSellerOrderMapper sellerOrderMapper;
//    private final ErpOrderInfoStatisticsMapper orderInfoStatisticsMapper;
    private final ErpSellerOrderLogMapper orderLogMapper;
    private final IErpSellerOrderLogService orderLogService;
    private final ErpSellerChildOrderMapper childOrderMapper;
//    private final ErpChildOrderStatisticsMapper childOrderStatisticsMapper;
    private final ErpSellerChildOrderExtendMapper erpSellerChildOrderExtendMapper;

    @Override
    public List<ErpSendOutGoods> getSendGoodsCountByOrderId(Long orderId) {
        return baseMapper.selectList(new LambdaQueryWrapper<ErpSendOutGoods>().eq(ErpSendOutGoods::getOrderId, orderId).eq(ErpSendOutGoods::getIsUse, 1));
    }

    @Override
    public ErpSendOutGoods getSendGoodsByChildOrderId(String childOrderId) {
        return baseMapper.selectOne(new LambdaQueryWrapper<ErpSendOutGoods>().eq(ErpSendOutGoods::getChildOrderId, childOrderId).eq(ErpSendOutGoods::getIsUse, 1));
    }

    /**
     * 查询订单发货
     */
    @Override
    public ErpSendOutGoodsVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询订单发货列表
     */
    @Override
    public TableDataInfo<ErpSendOutGoodsVo> queryPageList(ErpSendOutGoodsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpSendOutGoods> lqw = buildQueryWrapper(bo);
        Page<ErpSendOutGoodsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(vo -> {
            ErpSellerOrder order = sellerOrderMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId, vo.getOrderId()));
            if (order != null) {
                vo.setErpInnerOrderStatus(order.getErpInnerOrderStatus());
                vo.setLeftEndGoodTime(order.getLeftEndGoodTime());
            }
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询订单发货列表
     */
    @Override
    public List<ErpSendOutGoodsVo> queryList(ErpSendOutGoodsBo bo) {
        LambdaQueryWrapper<ErpSendOutGoods> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpSendOutGoods> buildQueryWrapper(ErpSendOutGoodsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpSendOutGoods> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getOrderId() != null, ErpSendOutGoods::getOrderId, bo.getOrderId());
        lqw.eq(StringUtils.isNotBlank(bo.getTrackingNo()), ErpSendOutGoods::getTrackingNo, bo.getTrackingNo());
        lqw.eq(StringUtils.isNotBlank(bo.getFpxTrackingNo()), ErpSendOutGoods::getFpxTrackingNo, bo.getFpxTrackingNo());
        lqw.eq(StringUtils.isNotBlank(bo.getShippingNo()), ErpSendOutGoods::getShippingNo, bo.getShippingNo());
        lqw.eq(StringUtils.isNotBlank(bo.getOnlineLogisticsLabel()), ErpSendOutGoods::getOnlineLogisticsLabel, bo.getOnlineLogisticsLabel());
        lqw.eq(bo.getIsUse() != null, ErpSendOutGoods::getIsUse, bo.getIsUse());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpSendOutGoods::getRevision, bo.getRevision());
        lqw.eq(StringUtils.isNotBlank(bo.getChildOrderId()), ErpSendOutGoods::getChildOrderId, bo.getChildOrderId());
        lqw.orderByDesc(ErpSendOutGoods::getCreateTime);
        return lqw;
    }

    /**
     * 新增订单发货
     */
    @Override
    public Boolean insertByBo(ErpSendOutGoodsBo bo) {
        ErpSendOutGoods add = BeanUtil.toBean(bo, ErpSendOutGoods.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改订单发货
     */
    @Override
    public Boolean updateByBo(ErpSendOutGoodsBo bo) {
        ErpSendOutGoods update = BeanUtil.toBean(bo, ErpSendOutGoods.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpSendOutGoods entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除订单发货
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional
    public R<Object> updateOrInsertProof(ErpSendOutGoodsBo bo) {
        Long orderId = bo.getOrderId();
        String childOrderId = bo.getChildOrderId();
        String proof = bo.getProof();
        String cnTrackingNo = bo.getTrackingNo();
        String purchasePrice = bo.getPurchasePrice();
        //1-4px 2-线下发货 3-骏捷云仓
        Integer type = bo.getType();

        //保存数据到子订单延伸表
        ErpSellerChildOrderExtend childOrderExtend = erpSellerChildOrderExtendMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerChildOrderExtend>().eq(ErpSellerChildOrderExtend::getChildOrderId, childOrderId)
        );
        if (childOrderExtend == null) {
            childOrderExtend = new ErpSellerChildOrderExtend();
            childOrderExtend.setChildOrderId(Long.valueOf(childOrderId));
            childOrderExtend.setOrderId(orderId);
        }
        childOrderExtend.setType(type);
        childOrderExtend.setType(bo.getType());
        childOrderExtend.setProof(proof);
        childOrderExtend.setCnTrackingNo(cnTrackingNo);
        childOrderExtend.setPurchasePrice(Double.valueOf(purchasePrice));
        erpSellerChildOrderExtendMapper.insertOrUpdate(childOrderExtend);

        ErpSendOutGoods erpSendOutGoods = BeanUtil.toBean(bo, ErpSendOutGoods.class);
        baseMapper.updateById(erpSendOutGoods);

        // 判断该订单的子订单是否全部填写国内运单号和凭证
        Integer countByOrderId = childOrderMapper.getChildCountByOrderId(orderId);
        List<ErpSellerChildOrderExtend> childOrderExtends = erpSellerChildOrderExtendMapper.selectList(
                new LambdaQueryWrapper<ErpSellerChildOrderExtend>()
                        .eq(ErpSellerChildOrderExtend::getOrderId, orderId)
                        .isNotNull(ErpSellerChildOrderExtend::getCnTrackingNo)
                        .isNotNull(ErpSellerChildOrderExtend::getProof)
        );


//        List<ErpSellerChildOrderExtend> collect = childOrderExtends.stream().filter(
//                        childOrder -> childOrder.getCnTrackingNo() != null && childOrder.getProof() != null)
//                .collect(Collectors.toList());
        if (childOrderExtends.size() == countByOrderId) {
            ErpSellerOrder sellerOrder = sellerOrderMapper.selectOne(new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId, orderId));
            ErpSellerOrderLog statusIntro = orderLogService.getStatusIntro(orderId);
            if (type == 2) {
                sellerOrder.setErpInnerOrderStatus("108");
                sellerOrder.setOrderStatus("offline");
                statusIntro.setCurrentStatus("108");
            } else {
                sellerOrder.setErpInnerOrderStatus("105");
                sellerOrder.setOrderProcessFlag("cainiao");
                statusIntro.setCurrentStatus("105");
            }
            orderLogService.updateByBo(BeanUtil.toBean(statusIntro, ErpSellerOrderLogBo.class));
            sellerOrderMapper.updateById(sellerOrder);

            //TODO 将实际采购价存入统计表
            /*ErpChildOrderStatistics childOrderStatistics = childOrderStatisticsMapper.selectOne(new LambdaQueryWrapper<ErpChildOrderStatistics>().eq(ErpChildOrderStatistics::getChildOrderId, childOrderId));
            if (ObjectUtils.isNotEmpty(childOrderStatistics)) {
                childOrderStatistics.setRealityPurchasePrice(purchasePrice);
                childOrderStatisticsMapper.updateById(childOrderStatistics);
            }

            // 取出所有真实采购价格
            BigDecimal purchaseTotal = BigDecimal.ZERO;
            List<ErpChildOrderStatistics> childOrderStatisticsList = childOrderStatisticsMapper.selectList(new LambdaQueryWrapper<ErpChildOrderStatistics>().eq(ErpChildOrderStatistics::getOrderId, orderId));
            for (ErpChildOrderStatistics erpChildOrderStatistics : childOrderStatisticsList) {
                String realityPurchasePrice = erpChildOrderStatistics.getRealityPurchasePrice();
                purchaseTotal = new BigDecimal(realityPurchasePrice).add(purchaseTotal);
            }
            ErpOrderInfoStatistics statistics = orderInfoStatisticsMapper.selectOne(new LambdaQueryWrapper<ErpOrderInfoStatistics>().eq(ErpOrderInfoStatistics::getOrderId, orderId));
            statistics.setRealPurchase(purchaseTotal.toString());
            orderInfoStatisticsMapper.updateById(statistics);*/

            //插入日志
            if (type == 2) {
                //线下发货
                orderLogService.createOrderLog(orderId, childOrderId, OrderLogType.UploadProof, null, OrderProcessFlag.Offline.getInfo(), "103");
            } else {
                orderLogService.createOrderLog(orderId, childOrderId, OrderLogType.UploadProof, null, OrderProcessFlag.CaiNiao.getInfo(), "103");
            }
        }


        return R.ok();
    }

    @Override
    public ErpSendOutGoods querySendGoodsInfo(ErpSendOutGoodsBo bo) {
        bo.setIsUse(1);
        LambdaQueryWrapper<ErpSendOutGoods> wrapper = buildQueryWrapper(bo);
        ErpSendOutGoods erpSendOutGoods = baseMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(erpSendOutGoods)) {
            erpSendOutGoods = new ErpSendOutGoods();
            erpSendOutGoods.setChildOrderId(bo.getChildOrderId());
            ErpSellerChildOrder childOrder = childOrderMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getChildOrderId, bo.getChildOrderId())
            );
            erpSendOutGoods.setOrderId(childOrder.getOrderId());
            erpSendOutGoods.setIsUse("1");
            baseMapper.insert(erpSendOutGoods);
        }

        return baseMapper.selectOne(wrapper);
    }

    @Override
    public List<ErpSendOutGoods> querySendGoodsInfoList(Long orderId) {
        ErpSendOutGoodsBo bo = new ErpSendOutGoodsBo();
        bo.setIsUse(1);
        bo.setOrderId(orderId);
        LambdaQueryWrapper<ErpSendOutGoods> wrapper = buildQueryWrapper(bo);
        return baseMapper.selectList(wrapper);
    }

//    @Override
//    public R<String> oldOrderSkuWarehousing(ErpSendOutGoodsBo bo) {
//        AffterentParam publicParam = new AffterentParam();
//        publicParam.setAppKey(FPS_APP_KEY);
//        publicParam.setAppSecret(FPS_APP_SECRET);
//        publicParam.setFormat("json");
//        publicParam.setVersion("1.0.0");
//        publicParam.setLanguage("CN");
//        publicParam.setMethod("fu.wms.sku.getlist");
//        List<Long> orderIds = param.getOrderIds();
//        for (Long orderId : orderIds) {
//
//            ErpSellerOrder erpSellerOrder = sellerOrderMapper.selectOne(new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId, orderId));
//            List<ErpSellerChildOrder> childOrderList = sellerChildOrderMapper.selectList(new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getOrderId, orderId));
//
//            for (ErpSellerChildOrder erpSellerChildOrder : childOrderList) {
//
//                // 获取sku信息
//                String skuCode = erpSellerChildOrder.getSkuCode();
//                ErpCollectProductSku skuInfo = collectProductSkuMapper.selectOne(new LambdaQueryWrapper<ErpCollectProductSku>().eq(ErpCollectProductSku::getSkuCode, skuCode));
//                //判断当前订单的sku是否存在
//                if (skuInfo != null) {
//                    //判断发货仓是否设置
//                    List<AeLogisticsServiceName> aeLogisticsServiceNameList = iErpSellerOrderService.logisticsServiceQuery(orderId, erpSellerOrder.getSellerLoginId());
//                    if (aeLogisticsServiceNameList.size() == 0) {
//                        return R.fail("您未设置系统推荐发货仓");
//                    }
//                    List<String> skuCodeList = new ArrayList<>();// 存放skuCode,用来查询是否需要创建sku
//                    skuCodeList.add(skuCode);
//                    String skuByCode = getSkuByCode(skuCodeList, publicParam);
//                    JSONArray isSkuCode = JSONObject.parseObject(skuByCode).getJSONObject("data").getJSONArray("skulist");
//                    // 没有则创建sku
//                    if (isSkuCode == null || isSkuCode.size() == 0) {
//                        CreateSku createSku = new CreateSku();
//                        Declare_country_list declare_country_list = new Declare_country_list();
//                        ArrayList<Declare_country_list> declare_country_lists = new ArrayList<>();
//
//                        Long collectProductId = skuInfo.getCollectProductId();
//                        ErpCollectProductVo collectProductVo = collectProductService.queryById(collectProductId);
//                        ErpCollectProductExpand erpCollectProductExpand = collectProductExpandMapper.selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
//                                .eq(ErpCollectProductExpand::getCollectProductId, collectProductId));
//                        String hsCodeId = erpCollectProductExpand.getHsCode();//代表海关编码表的主键
//                        String hsCode = productHsMapper.selectById(Long.parseLong(hsCodeId)).getHsCode();
//                        createSku.setSku_code(skuCode);
//                        String categoryEn = collectProductService.getCategoryEn(collectProductId);
//                        String categoryCN = collectProductService.getCategoryCN(collectProductId);
//                        createSku.setSku_name(categoryEn);
//                        createSku.setChinese_name(categoryCN);
//                        createSku.setSales_link(skuInfo.getSkuBuyLink());
//                        createSku.setWeight(skuInfo.getSkuWeight());
//                        createSku.setLength(skuInfo.getSkuLength().doubleValue());
//                        createSku.setWidth(skuInfo.getSkuWidth().doubleValue());
//                        createSku.setHeight(skuInfo.getSkuHeight().doubleValue());
//                        createSku.setSpecification("一件代发");
//                        declare_country_list.setExport_country("CN");
//                        declare_country_list.setExport_declare(categoryEn);
//                        declare_country_list.setExport_declare_value(erpSellerChildOrder.getProductPrice());
//                        declare_country_list.setExport_currency(erpSellerChildOrder.getProductCurrencyCode());
//                        declare_country_list.setExport_hscode(hsCode);
//                        declare_country_list.setCountry("CN");
//                        declare_country_list.setImport_declare(categoryEn);
//                        declare_country_list.setDeclare_value(erpSellerChildOrder.getProductPrice());
//                        declare_country_list.setCurrency(erpSellerChildOrder.getProductCurrencyCode());
//                        declare_country_list.setHs_code(hsCode);
//                        declare_country_lists.add(declare_country_list);
//                        createSku.setDeclare_country_list(declare_country_lists);
//                        JSONObject createSkuJson = null;
//                        try {
//                            createSkuJson = JSONObject.parseObject(new JsonMapper().writeValueAsString(createSku));
//                        } catch (JsonProcessingException e) {
//                            throw new RuntimeException(e);
//                        }
//                        publicParam.setMethod("fu.wms.sku.newcreate");
//                        String createSkuReturn = ApiHttpClientUtils.apiJsongPost(publicParam, createSkuJson, AmbientEnum.FORMAT_ADDRESS);
//                        JSONObject skuJsonObject = JSONObject.parseObject(createSkuReturn);
//                        if ("0".equals(skuJsonObject.getString("result"))) {
//                            return R.fail(skuJsonObject.getJSONArray("errors").toString());
//                        }
//                    }
//                    //状态设为订单待采购
//                    iErpSellerOrderService.setInnerStatus(orderId, "103");
//                } else {
//                    //转为老订单待采购
//                    iErpSellerOrderService.setInnerStatus(orderId, "1031");
//                }
//                ErpSellerOrderLogBo orderLog = new ErpSellerOrderLogBo();
//                orderLog.setStatusIntro("订单提交待发货审核");
//                orderLog.setOrderId(orderId);
//                orderLog.setChildOrderId(erpSellerChildOrder.getChildOrderId());
//                String storeNameByUserName = empowerService.getStoreNameByUserName(erpSellerOrder.getSellerLoginId());
//                orderLog.setStoreName(storeNameByUserName);
//                String username = LoginHelper.getUsername();
//                orderLog.setErpAccount(username);
//                orderLogService.insertByBo(orderLog);
//            }
//        }
//    }
}
